#-*- coding:utf-8 -*-
import web
import configparser
import os
import json
from bluepy import btle
urls = (
    '/aa/(.*)', 'aa',
    '/hello/(.*)', 'hello',
    '/lemon/(.*)', 'lemon',
    '/fakeap/(.*)', 'fakeap',
)
# sudo python hhtest.py 192.168.1.104 8000
app = web.application(urls, globals())
os.chdir("/home/wuyou/jctx")
cf = configparser.ConfigParser()
filename = cf.read("attack.ini")
attackmac = cf.get("MAC","mac")
print attackmac
class aa:
    def GET(self,name):
        if not name:
            name='ssssss'
        return "hello"+name
class fakeap:
    def GET(self, fakeap):
        if not fakeap:
            fakeap = 'World'
        print fakeap
        cf.set("MAC","mac",fakeap)
        with open("fakeap.ini", "w+") as f:
            cf.write(f)


        return 'Hello, ' + fakeap + '!'

class hello:
    def GET(self, mac):
        if not mac:
            mac = 'World'
        print mac
        cf.set("MAC","mac",mac)
        with open("attack.ini", "w+") as f:
            cf.write(f)


        return 'Hello, ' + mac + '!'

class lemon:
    def getInfo(addr, addrType):
        # if properties=='READ', readType and readMsg
        info = {}  # {service1:{chara1:[handle, properties, readType, readMsg], chara2}}
        try:
            d = btle.Peripheral(addr, addrType)
        except:
            print 'connect failed......'
            return 1
        try:
            for ser in d.getServices():
                dict1 = {}
                for chara in ser.getCharacteristics():
                    list1 = []
                    list1.append(str(chara.getHandle()))
                    list1.append(chara.propertiesToString())
                    if (chara.supportsRead()):
                        list1.append(type(chara.read()))
                        list1.append(chara.read())
                    dict1[str(chara)] = list1
                info[str(ser)] = dict1
        except:
            print 'connect ended......'
            return 2
        d.disconnect()
        return info
    def GET(self,selectedMac):
        if not selectedMac:
            return 'please input volid mac'
        print selectedMac
        addr = selectedMac
        addrType = 'random'
        d = btle.Peripheral(addr, addrType)
        a = d.writeCharacteristic(14, '\x7e\x05\x08\x01\x82', withResponse=True)
        print a

        return json.dumps({'bleleak':a})



if __name__ == "__main__":
    app.run()
